package models

import (
	"database/sql"
	"html/template"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func init() {

}

func (this *Menu_gl) Get_left_menu() (ret template.HTML) {
	t := this.Get_menu_gl() //先执行调用
	for _, v1 := range t.Child {
		ret = ret + template.HTML("<li class='dropdown'><a href='"+v1.Url+"' class='dropdown-toggle' data-toggle='dropdown'>"+v1.Name+"<strong class='caret'></strong></a><ul class='dropdown-menu'>")
		for _, v2 := range v1.Child {
			ret = ret + template.HTML("<li><a href='"+v2.Url+"'>"+v2.Name+"</a></li>")
		}
		ret = ret + template.HTML("</ul></li>")
	}
	//log.Println("menu.go menu:", ret)
	return ret
}
func (this *Menu_gl) Get_right_menu() (ret template.HTML) {
	//user_name := template.HTML(User.User_name)
	ret = ret + "<li><a href=" + "/logout" + ">" + "<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>" + "注销" + "</a></li>"
	ret = ret + "<li><a href=" + "/user" + ">" + "<span class='glyphicon glyphicon-user' aria-hidden='true'></span>" + "用户管理" + "</a></li>"
	//ret = ret + "<li class='dropdown'><a href='" + "#" + "' class='dropdown-toggle' data-toggle='dropdown'>" + "用户管理" + " <strong class='caret'></strong></a>"
	//ret = ret + "<ul class='dropdown-menu'><li><a href='" + "#" + "'>" + "NAME" + "</a></li></ul></li>"
	//log.Println("menu.go menu:", ret)
	return ret
}

func (this *Menu_gl) Get_menu_gl() (ret Menu_gl) {
	//返回树型菜单，类型为树型结构体
	var (
		sqlstr string
		rows   *sql.Rows
		t      []Menu_gl
		i      int
		err    error
	)
	if db.Ping() != nil {
		log.Panicln("数据库已断开连接！")
	}
	sqlstr = "SELECT menu_id, parentid, menu_name, menu_url FROM t1_menu WHERE deleted<1 and hide<1 ORDER BY sort ASC"
	rows, err = db.Query(sqlstr)
	if err != nil {
		log.Println(err.Error())
		return
	}
	for rows.Next() { //开始循环读取字段
		var tmp Menu_gl
		i++
		err = rows.Scan(&tmp.Id, &tmp.Pid, &tmp.Name, &tmp.Url) //数据指针，会把得到的数据，往刚才id 和 lvs引入
		if err != nil {
			//log.Println("menu.go 取记录出错！")
		}
		//log.Println("menu.go Id:", tmp.Id, " Pid:", tmp.Pid, " Name:", tmp.Name, " Url:", tmp.Url)
		t = append(t, tmp) //将记录保存到切片
	}
	rows.Close()
	ret.Id = 0
	ret.Name = "menu"
	//从切片读取树型到结构，取第一层
	for k, v := range t {
		if v.Pid == 0 {
			ret.Child = append(ret.Child, &t[k])
		}
	}
	//第二层树
	for k1, v1 := range ret.Child {
		for k2, v2 := range t {
			if v2.Pid == v1.Id {
				ret.Child[k1].Child = append(ret.Child[k1].Child, &t[k2])
				//log.Println("menu.go Id:", v1.Id, ret.Child[k1], t[k2])
			}
		}
	}
	//输出json打印测试
	//json_data, err := json.MarshalIndent(ret, "", "  ") //json.Marshal(data)
	//if err != nil {
	//	log.Panicf("JSON marshaling failed: %s", err)
	//}
	//log.Printf("menu.go %s\n", json_data)
	return ret
}

func xxdy(ms []Menu_gl) {
	//循环讯取menu_gl切片，进行处理成树结构的Menu_gl结构体
	//var m Menu_gl
}
